package com.gz.mylife.im;

import java.util.List;

import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.mylife.R;
import com.gz.mylife.app.HDImagePreview;
import com.gz.mylife.util.EmojiUtil;
import com.gz.mylife.util.ImageUtils;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.BetterPopupWindow;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.account.po.UserInfo;
import com.zl.smartmall.library.listener.ReportPersonListener;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;

public class ChatSessionAdapter extends BaseAdapter implements OnLongClickListener{

	private static final String TAG = "ChatSessionAdapter";

	private ChatSession mActivity;
	private Context mContext;
	private LayoutInflater mInflater;
	private ListView mListView;
	
	private int mPhotoSize;
	private ImageSize mSize;
	private List<IMessage> mMessages;
	private DisplayImageOptions mOptions;
	private DisplayImageOptions mFaceOptions;
	
	private UserInfo mCurrUser;
	private SessionBean mSession;
//	private AsyncHttpClient mHttpClient;
	
	public static interface IMsgViewType {
		int IMVT_COM_MSG = 0;
		int IMVT_TO_MSG = 1;
	}

	public ChatSessionAdapter(ChatSession activity, ListView listView,List<IMessage> list) {
		mActivity = activity;
		mContext = activity.getApplicationContext();
		mMessages = list;
		mListView = listView ; 
		mSession = activity.getCurrentSession();
		mCurrUser = IAuth.getInstance().loadUserInfo();
		mInflater = LayoutInflater.from(activity.getApplicationContext());
		mOptions  = buildImageOptions();
		mFaceOptions = buildFaceOptions();
		
		mPhotoSize = mActivity.getResources().getDimensionPixelSize(R.dimen.chatroom_photo_size);
		mSize = new ImageSize(mPhotoSize,mPhotoSize);
	}
	
	private DisplayImageOptions buildImageOptions(){
		return new DisplayImageOptions.Builder()
        //.resetViewBeforeLoading()
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory(true)
        .cacheOnDisk(true)
//        .showStubImage(R.drawable.ic_launcher)
//        .showImageOnFail(R.drawable.ic_launcher)
        .imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
        .displayer(new RoundedBitmapDisplayer(Tools.dip2px(mContext, 2)))
        .build();
	}
	
	private DisplayImageOptions buildFaceOptions(){
		return new DisplayImageOptions.Builder()
        .resetViewBeforeLoading()
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory()
        .cacheOnDisc()
        //.showStubImage(R.drawable.picture_frame)
//        .showImageOnFail(R.drawable.picture_frame)
        .imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
//        .displayer(new RoundedBitmapDisplayer(8))
        .build();
	}

	@Override
	public int getCount() {
		return mMessages.size();
	}

	@Override
	public Object getItem(int position) {
		return mMessages.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getItemViewType(int position) {
		IMessage bean = mMessages.get(position);
		if (bean.isComMsg()) {
			return IMsgViewType.IMVT_COM_MSG;
		} else {
			return IMsgViewType.IMVT_TO_MSG;
		}
	}
	
	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		
		final IMessage bean = mMessages.get(position);
		final ViewHolder viewHolder;
		if (convertView == null) {
			if (bean.isComMsg()) {
				convertView = mInflater.inflate(R.layout.chatroom_msg_item_right, null);
			} else {
				convertView = mInflater.inflate(R.layout.chatroom_msg_item_left, null);
			}

			viewHolder = new ViewHolder();
			viewHolder.ivFace = (ImageView) convertView.findViewById(R.id.face_iv);
			viewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.date_tv);
			viewHolder.txt_nickname = (TextView) convertView.findViewById(R.id.txt_nickname);
			viewHolder.tvContent = (TextView) convertView.findViewById(R.id.content_tv);
			viewHolder.ivImage = (ImageView) convertView.findViewById(R.id.image_iv);
			viewHolder.layoutImage = (ViewGroup) convertView.findViewById(R.id.layout_image);
			viewHolder.progressBar = (ProgressBar) convertView.findViewById(R.id.ProgressBar);
			viewHolder.iv_msg_resend = (ImageView) convertView.findViewById(R.id.iv_msg_resend);

			viewHolder.layout_get_more = (RelativeLayout) convertView.findViewById(R.id.layout_get_more);
			viewHolder.btn_load = (Button) convertView.findViewById(R.id.btn_load);
			viewHolder.pd_load = (ProgressBar) convertView.findViewById(R.id.pb_load);
			
			viewHolder.rl_notify = (RelativeLayout) convertView.findViewById(R.id.rl_notify);
			viewHolder.rl_content = (RelativeLayout) convertView.findViewById(R.id.right_ll);
			
			viewHolder.txt_nickname.setVisibility(View.GONE);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		
		if(bean.inMsgState == IMessage.STATE_UPLOADING){
			viewHolder.progressBar.setVisibility(View.VISIBLE);
			viewHolder.iv_msg_resend.setVisibility(View.GONE);
		} else if(bean.inMsgState == IMessage.STATE_FAILURE){
			viewHolder.progressBar.setVisibility(View.GONE);
			viewHolder.iv_msg_resend.setVisibility(View.VISIBLE);
		} else {
			viewHolder.ivImage.setOnClickListener(previewListener);
			viewHolder.progressBar.setVisibility(View.GONE);
			viewHolder.iv_msg_resend.setVisibility(View.GONE);
		}
		
		if(bean.inShowTime){
			viewHolder.tvSendTime.setVisibility(View.VISIBLE);
		} else {
			viewHolder.tvSendTime.setVisibility(View.GONE);
		}
		viewHolder.layout_get_more.setVisibility(View.GONE);
		viewHolder.tvSendTime.setText(Tools.formatTimeStampString(mContext, bean.getDateline(), false));
		if(bean.getMyType() != -1){
			viewHolder.rl_notify.setVisibility(View.GONE);
			viewHolder.rl_content.setVisibility(View.VISIBLE);
			if(bean.getMyType() == 1||bean.getMyType() == 2){
				viewHolder.layoutImage.setVisibility(View.GONE);
				viewHolder.tvContent.setVisibility(View.VISIBLE);
				viewHolder.tvContent.setText("分享了《"+EmojiUtil.getEmotionString(mContext, bean.getContent(), Tools.dip2px(mContext, 22))+"》");
				viewHolder.tvContent.setTag(bean);
				viewHolder.tvContent.setOnLongClickListener(this);
				viewHolder.tvContent.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
//						if(bean.getMyType() == 1){
//							Intent intent = new Intent(mActivity, InvitationDetail.class);
//							intent.putExtra("discuz_id", bean.getDiscuzId());
//							intent.putExtra("tie_id", bean.getTopicId());
//							mActivity.startActivity(intent);
//						}else{
//							Intent intent = new Intent(mActivity, NewsInvitation.class);
//							intent.putExtra("discuzId", bean.getDiscuzId());
//							intent.putExtra("topicId", bean.getTopicId());
//							intent.putExtra("title", bean.getContent());
//							intent.putExtra("url", bean.getTieUrl());
//							intent.putExtra("reply", 0);
//							mActivity.startActivity(intent);
//						}
					}
				});
			}else{
				if (bean.getShowType() == IMessage.TYPE_TEXT) {
					viewHolder.layoutImage.setVisibility(View.GONE);
					viewHolder.tvContent.setVisibility(View.VISIBLE);
					viewHolder.tvContent.setText(EmojiUtil.getEmotionString(mContext, bean.getContent(), Tools.dip2px(mContext, 22)));
				
					viewHolder.tvContent.setTag(bean);
					viewHolder.tvContent.setOnLongClickListener(this);
				} else if(bean.getShowType() == IMessage.TYPE_PHOTO) {
					viewHolder.layoutImage.setVisibility(View.VISIBLE);
					viewHolder.tvContent.setVisibility(View.GONE);
					
					viewHolder.ivImage.setTag(bean);
					viewHolder.ivImage.setOnLongClickListener(this);
					//Log.e("pic", "" + bean.getPicture());
					// 显示本地图片
					if(bean.inMsgState == IMessage.STATE_NORMAL){
						//Object urlObj = viewHolder.ivImage.getTag();
						//if(urlObj==null || !urlObj.equals(bean.getPicture())){
							ImageSize showSize = getReasonSize(bean.getWidth(),bean.getHeight());
							LayoutParams params = viewHolder.ivImage.getLayoutParams();
							params.width = showSize.getWidth();
							params.height = showSize.getHeight();
							viewHolder.ivImage.setLayoutParams(params);
							//Log.e("params", String.format("w:%s, h:%s",  bean.getWidth(), bean.getHeight()));
							ImageLoader.getInstance().displayImage(bean.getPicture(),viewHolder.ivImage, mOptions);
							//viewHolder.ivImage.setTag(bean.getPicture());
						//} 
					} else {
						//XXX 只有在上传过程中的ImageView 判断加载了图片就不显示
						Drawable drawable = viewHolder.ivImage.getDrawable();
						if(drawable == null){
							Bitmap bitmap = Tools.getFitBitmap(bean.getPicture(),mSize.getWidth());
							
							if (bitmap != null) {
								Bitmap roundedCornerBitmap = ImageUtils.getRoundedCornerBitmap(bitmap,5);
								ImageSize showSize = getReasonSize(bitmap.getWidth(),bitmap.getHeight());
								LayoutParams params = viewHolder.ivImage.getLayoutParams();
								params.width = showSize.getWidth();
								params.height = showSize.getHeight();
								viewHolder.ivImage.setLayoutParams(params);
								viewHolder.ivImage.setImageBitmap(roundedCornerBitmap);
							}
						}
					}
				} else {
					viewHolder.layoutImage.setVisibility(View.GONE);
					viewHolder.tvContent.setVisibility(View.VISIBLE);
					viewHolder.tvContent.setText("[不能识别的类型]");
				}
			}
	
			// 头像显示
			String face = bean.isComMsg()? mCurrUser.getFace() : mSession.getFace();
			final int uid = bean.isComMsg()? mCurrUser.getUid(): mSession.getFuid();
			
	//		ImageLoader.getInstance().displayImage(face, viewHolder.ivFace, mFaceOptions);
			ImageLoader.getInstance().displayImage(face, viewHolder.ivFace,new SimpleImageLoadingListener(){
				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					if (view != null && view instanceof ImageView)
						((ImageView) view).setImageBitmap(loadedImage);
				}
	
				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
					if (view != null && view instanceof ImageView) {
						((ImageView) view).setImageResource(R.drawable.ic_load_image_square_default);
					}
				}
			});
			
			viewHolder.ivFace.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					int fuid = uid;
//					if(fuid == IAuth.getInstance().loadUserInfo().getUid()){
//						Intent intent = new Intent();
//						intent.setClass(mContext, MyProfileSelf.class);
//						intent.putExtra("fuid", fuid);
//						mActivity.startActivity(intent);
//					}else{
//						Intent intent = new Intent();
//						intent.setClass(mContext, MyProfileOther.class);
//						intent.putExtra("fuid", fuid);
//						mActivity.startActivity(intent);
//					}
				}
			});
		}else{
			viewHolder.rl_notify.setVisibility(View.VISIBLE);
			viewHolder.rl_content.setVisibility(View.GONE);
		}
		return convertView;
	}
	
	public void updateView(int index) {
		int currIndex = index+1;
		int visiblePosition = mListView.getFirstVisiblePosition();
		if (currIndex - visiblePosition >= 0) {
			CrashHandler.d(TAG, "visiblePosition:"+visiblePosition);
			CrashHandler.d(TAG, "currIndex:"+currIndex);
			CrashHandler.d(TAG, "mListView.getSelectedItemId:"+mListView.getSelectedItemId());
			View view = mListView.getChildAt(currIndex - visiblePosition);
			ViewHolder viewHolder = (ViewHolder) view.getTag();
			
			final IMessage bean = mMessages.get(index);
			
			// 计算最后的显示时间
			MessageDao.filterSingleShowTime(mMessages,index);
			
			if(bean.inMsgState == IMessage.STATE_UPLOADING){
				viewHolder.progressBar.setVisibility(View.VISIBLE);
				viewHolder.iv_msg_resend.setVisibility(View.GONE);
			} else if(bean.inMsgState == IMessage.STATE_FAILURE){
				viewHolder.progressBar.setVisibility(View.GONE);
				viewHolder.iv_msg_resend.setVisibility(View.VISIBLE);
			} else {
				viewHolder.ivImage.setOnClickListener(previewListener);
				viewHolder.progressBar.setVisibility(View.GONE);
				viewHolder.iv_msg_resend.setVisibility(View.GONE);
			}
			
			viewHolder.tvSendTime.setText(Tools.formatTimeStampString(mActivity, bean.getDateline(), false));
			if(bean.getMyType() == 1 || bean.getMyType() == 2){
				viewHolder.layoutImage.setVisibility(View.GONE);
				viewHolder.tvContent.setVisibility(View.VISIBLE);
				viewHolder.tvContent.setText("分享了《"+EmojiUtil.getEmotionString(mContext, bean.getContent(), Tools.dip2px(mContext, 22))+"》");
				viewHolder.tvContent.setTag(bean);
				viewHolder.tvContent.setOnLongClickListener(this);
				viewHolder.tvContent.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
//						if(bean.getMyType() == 1){
//							Intent intent = new Intent(mActivity, InvitationDetail.class);
//							intent.putExtra("discuz_id", bean.getDiscuzId());
//							intent.putExtra("tie_id", bean.getTopicId());
//							mActivity.startActivity(intent);
//						}else{
//								Intent intent = new Intent(mActivity, NewsInvitation.class);
//								intent.putExtra("discuzId", bean.getDiscuzId());
//								intent.putExtra("topicId", bean.getTopicId());
//								intent.putExtra("title", bean.getContent());
//								intent.putExtra("url", bean.getTieUrl());
//								intent.putExtra("reply", 0);
//								mActivity.startActivity(intent);
//						}
					}
				});
			}else{
				if(bean.getShowType() == IMessage.TYPE_PHOTO){
					viewHolder.ivImage.setOnClickListener(previewListener);
					viewHolder.ivImage.setTag(bean.getPicture());
					viewHolder.layoutImage.setVisibility(View.VISIBLE);
					viewHolder.tvContent.setVisibility(View.GONE);
					//ImageLoader.getInstance().displayImage2(bean.getPicture(),viewHolder.ivImage,mOptions,mSize);
					
					viewHolder.ivImage.setTag(bean);
					viewHolder.ivImage.setOnLongClickListener(this);
				} else if (bean.getShowType() == IMessage.TYPE_AUDIO) {
				} else {
					//这里要处理分享和文本两种内容
					viewHolder.layoutImage.setVisibility(View.GONE);
					viewHolder.tvContent.setVisibility(View.VISIBLE);
					viewHolder.tvContent.setText(EmojiUtil.getEmotionString(mContext, bean.getContent(), Tools.dip2px(mContext, 22)));
					
					viewHolder.tvContent.setTag(bean);
					viewHolder.tvContent.setOnLongClickListener(this);
				}
			}
			
		}		
	}
	
	OnClickListener previewListener = new  OnClickListener(){
		@Override
		public void onClick(View v) {
			String picture = ((IMessage)v.getTag()).getPicture();
			Log.e("simage", picture);
			if(mActivity!=null && !TextUtils.isEmpty(picture)){
				String[] images = {IMGParams.getBigImageUrl(picture)};
				Intent intent = new Intent();
				intent.putExtra("images", images);
				Log.e("bimage", IMGParams.getBigImageUrl(picture));
				intent.setClass(mActivity, HDImagePreview.class);
				mActivity.startActivity(intent);
			}
		}
	};
	
	@Override
	public boolean onLongClick(View arg0) {
		IMessage msg = (IMessage) arg0.getTag();
		if (msg == null) {
			return true;
		}
		if(!(arg0.getTag() instanceof IMessage) || (msg.getShowType() == IMessage.TYPE_PHOTO && (!msg.isComMsg()||(msg.inMsgState != ChatMessage.STATE_FAILURE)))){
			return true;
		}
		DemoPopupWindow dw = new DemoPopupWindow(arg0, msg);
//		dw.showLikeQuickAction(40, 60);
		
		dw.showLikeQuickAction(0, arg0.getHeight()/2);
		return true;
	}
	
	/**
	 * Extends {@link BetterPopupWindow}
	 * <p>
	 * Overrides onCreate to create the view and register the button listeners
	 * @author qbert
	 * 
	 */
	private class DemoPopupWindow extends BetterPopupWindow implements OnClickListener {
		public DemoPopupWindow(View anchor,IMessage message) {
			super(anchor);
			mMessage = message;
			init();
		}
		View mCopy;
		View mResend;
		View mReport;
		View reportLine;
		View mResendLine;
		private IMessage mMessage;
		
		@Override
		protected void onCreate() {
			// inflate layout
			LayoutInflater inflater = (LayoutInflater) this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			ViewGroup root = (ViewGroup) inflater.inflate(R.layout.popup_oper, null);
			mCopy = root.findViewById(R.id.txt_copy);
			mResend = root.findViewById(R.id.layout_resend);
			mReport = root.findViewById(R.id.layout_report);
			reportLine = root.findViewById(R.id.line);
			mResendLine = root.findViewById(R.id.divid_resend);
			mCopy.setOnClickListener(this);
			mResend.setOnClickListener(this);
			mReport.setOnClickListener(this);
			
			//int index = mActivity.mChatService.findIndexByUUID(mUUID);
			//IMessage message = mMessages.get(index);
//			if(mMessage.getShowType() == IMessage.TYPE_PHOTO){
//				mCopy.setVisibility(View.GONE);
//			}
			// set the inflated view as what we want to display
			this.setContentView(root);
		}

		void init(){
			if(mMessage.inMsgState == IMessage.STATE_NORMAL){
				boolean isPhoto = mMessage.getShowType() == IMessage.TYPE_PHOTO;
				mCopy.setVisibility(isPhoto ? View.GONE : View.VISIBLE);
				mResend.setVisibility(View.GONE);
				mReport.setVisibility(mMessage.isComMsg() ? View.GONE : View.VISIBLE);
				reportLine.setVisibility(isPhoto ? View.GONE : View.VISIBLE);
			} else if(mMessage.inMsgState == IMessage.STATE_FAILURE){
				if(mMessage.getShowType() == IMessage.TYPE_PHOTO){
					mResendLine.setVisibility(View.GONE);
					mCopy.setVisibility(View.GONE);
					mResend.setVisibility(View.VISIBLE);
				} else {
					mCopy.setVisibility(View.VISIBLE);
					mResend.setVisibility(View.VISIBLE);
				}
				mReport.setVisibility(View.GONE);
			}
		}
		
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override
		public void onClick(View v) {
			if(v.getId() == R.id.txt_copy){
				if(mMessage!= null){
					int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                    if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
                        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("label",mMessage.getContent());
                        clipboard.setPrimaryClip(clip);
                    } else {
                        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboard.setText(mMessage.getContent());
                    }
				}
			} else if(v.getId() == R.id.layout_resend){
				if(mMessage!= null){
					int index = mActivity.mChatService.findIndexByUUID(mMessage.inUUID);
					IMessage message = mMessages.get(index);
					if(message.getShowType() == IMessage.TYPE_TEXT){
						mActivity.mChatService.resendTextMessage(index);
					} else if(message.getShowType() == IMessage.TYPE_PHOTO){
						mActivity.mChatService.resendPhotoMessage(index);
					}
				}
			} else if (v.getId() == R.id.layout_report) {
				
//				String url = String.format(Constants.URL_REPORT_PERSON, 
//						mMessage.isComMsg() ? mMessage.getFromUid() : mMessage.getToUid(), "");
//				?uid=%s&reason=%s
				
				RequestParams params = new RequestParams();
				params.put("uid", mMessage.isComMsg() ? mMessage.getFromUid() : mMessage.getToUid());
				params.put("reason", "有问题");
				SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
				SingtonAsyncHttpClient.getInstance().get(Constants.URL_REPORT_PERSON, params, new ReportPersonListener() {
					
					@Override
					public void onResponseFailed() {
						// TODO Auto-generated method stub
						ToastUtils.showToast(mActivity, "举报失败, 请重试");
					}
					
					@Override
					public void onOffline() {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onNoNetWork() {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onResponseSuccess() {
						// TODO Auto-generated method stub
						ToastUtils.showToast(mActivity, "举报成功");
					}
				});
			}
			
			this.dismiss();
		}
	}
	
	public static class ViewHolder { 
		public TextView tvSendTime;
		public ImageView ivFace;
		public TextView txt_nickname;
        public TextView tvContent;
        public ImageView ivImage;
        public ViewGroup layoutImage;
        public ProgressBar progressBar;
        public ImageView iv_msg_resend;
        
        public RelativeLayout layout_get_more;
        public ProgressBar pd_load;
        public Button btn_load;
        
        public RelativeLayout rl_notify;
        public RelativeLayout rl_content;
        
        public boolean isComMsg = true;
    }

	// 计算合理的大小
	public ImageSize getReasonSize(int width,int height){
		if(width < mPhotoSize/2){
			width = mPhotoSize/2;
		} else if(width > mPhotoSize){
			width = mPhotoSize;
		} 
		if(height < mPhotoSize/2){
			height = mPhotoSize/2;
		} else if(height > mPhotoSize){
			height = mPhotoSize;
		}
		return new ImageSize(width,height);
	}

}
